package com.hwadee.property.controller.charge;

import com.hwadee.property.dto.ChargeDetailPersonal;
import com.hwadee.property.dto.PageResult;
import com.hwadee.property.pojo.ChargeDetail;
import com.hwadee.property.service.*;
import com.hwadee.property.util.*;
import io.jsonwebtoken.JwtException;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/charge-details")
@Api(tags = "缴费详情-ChargeDetailController")
@CrossOrigin
public class ChargeDetailController {

    @Autowired
    private IChargeDetailService chargeDetailService;

    @Autowired
    private IUserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/personal")
    @ApiOperation(value = "【业主】查询本人需缴费用", notes = "根据业主ID获取用户个人需缴费用。缴费状态——0：未缴费，1：已缴费")
    public AjaxResult getChargeDetailsByOwnerId(@RequestHeader("Authorization") String token) {
        jwtUtil.verifyToken(token);

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 根据用户ID查询缴费条目信息
            List<ChargeDetailPersonal> chargeDetailPersonalList = chargeDetailService.listByOwnerId(userId);

            // 返回缴费条目信息
            return AjaxResult.success(chargeDetailPersonalList);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.error("查询缴费信息失败");
        }
    }

    @PostMapping("/property/add")
    @ApiOperation(value = "【物业】生成小区当月缴费订单", notes = "新增小区缴费订单列表，涵盖当月的水费、电费、燃气费。缴费状态——0：未缴费，1：已缴费")
    public AjaxResult addChargeDetail(@RequestHeader("Authorization") String token,
                                      @RequestParam Integer month) {
        // 参数校验
        if (token == null || token.isEmpty()) {
            return AjaxResult.error(ErrorCodes.UNAUTHORIZED, "未授权, token 为空");
        }
        if (month == null || month < 1 || month > 12) {
            return AjaxResult.error(ErrorCodes.INVALID_PARAMETER, "月份参数无效，应为 1-12 之间的整数");
        }

        try {
            // 从 token 解析用户 ID
            Long userId = jwtUtil.getUserId(token);
            if (userId == null) {
                throw new BusinessException(ErrorCodes.UNAUTHORIZED, "用户身份解析失败，token 可能无效");
            }

            // 调用 Service 生成缴费订单
            List<ChargeDetail> chargeDetails = chargeDetailService.addChargeDetailByProperty(userId, month);
            return AjaxResult.success(chargeDetails);
        } catch (BusinessException e) {
            return AjaxResult.error(e.getCode(), e.getMessage()); // 业务异常
        } catch (JwtException e) {
            return AjaxResult.error(ErrorCodes.UNAUTHORIZED, "身份认证失败，token 解析异常：" + e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error(ErrorCodes.SERVER_ERROR, "生成小区当月缴费订单失败：" + e.getMessage());
        }
    }


    @GetMapping("/property/page")
    @ApiOperation(value = "【物业】查询小区收费明细分页", notes = "根据筛选条件查询收费明细的分页数据。缴费状态——0：未缴费，1：已缴费")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "用户授权token", required = true, paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "current", value = "当前页码", defaultValue = "1", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页显示条数", defaultValue = "10", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "ownerId", value = "业主ID", required = false, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "houseId", value = "房屋ID", required = false, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "chargeId", value = "收费项目ID", required = false, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "propertyStaffId", value = "物业人员ID", required = false, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "feeMonth", value = "费用月", required = false, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "paymentStatus", value = "缴费状态（0：未缴费，1：已缴费）", defaultValue = "0", paramType = "query", dataType = "int", required = true)
    })

    public AjaxResult getPage(@RequestHeader("Authorization") String token,
                              @RequestParam(value = "current", defaultValue = "1") int current,
                              @RequestParam(value = "size", defaultValue = "10") int size,
                              @RequestParam(value = "ownerId", required = false) Long ownerId,
                              @RequestParam(value = "houseId", required = false) Long houseId,
                              @RequestParam(value = "chargeId", required = false) Long chargeId,
                              @RequestParam(value = "propertyStaffId", required = false) Long propertyStaffId,
                              @RequestParam(value = "feeMonth", required = false) Integer feeMonth,
                              @RequestParam(value = "paymentStatus", defaultValue = "0") int paymentStatus) {
        // 如果token为null或为空字符串，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.error("未授权, token 为空");
        }


        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 返回结果
            return getPage(token, current, size, ownerId, userService.getById(userId).getCommunityId(),
                    houseId, chargeId, propertyStaffId, feeMonth, paymentStatus);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.error("生成小区当月缴费订单失败" + e.getMessage());
        }
    }

    @GetMapping("/page")
    @ApiOperation(value = "【管理员】获取收费明细分页列表", notes = "根据筛选条件查询收费明细的分页数据。缴费状态——0：未缴费，1：已缴费")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", defaultValue = "1", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "size", value = "每页显示条数", defaultValue = "10", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "ownerId", value = "业主ID", paramType = "query", dataType = "Long", required = false),
            @ApiImplicitParam(name = "communityId", value = "小区ID", paramType = "query", dataType = "Long", required = false),
            @ApiImplicitParam(name = "houseId", value = "房屋ID", paramType = "query", dataType = "Long", required = false),
            @ApiImplicitParam(name = "chargeId", value = "收费项目ID", paramType = "query", dataType = "Long", required = false),
            @ApiImplicitParam(name = "propertyStaffId", value = "物业员工ID", paramType = "query", dataType = "Long", required = false),
            @ApiImplicitParam(name = "feeMonth", value = "费用月份", paramType = "query", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "paymentStatus", value = "缴费状态（0：未缴费，1：已缴费）", defaultValue = "0", paramType = "query", dataType = "int", required = true)
    })

    public AjaxResult getPage(
            @RequestHeader("Authorization") String token,
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "ownerId", required = false) Long ownerId,
            @RequestParam(value = "communityId", required = false) Long communityId,
            @RequestParam(value = "houseId", required = false) Long houseId,
            @RequestParam(value = "chargeId", required = false) Long chargeId,
            @RequestParam(value = "propertyStaffId", required = false) Long propertyStaffId,
            @RequestParam(value = "feeMonth", required = false) Integer feeMonth,
            @RequestParam(value = "paymentStatus", defaultValue = "0") int paymentStatus) {
        PageResult<ChargeDetail> result = chargeDetailService.getPage(current, size, ownerId, communityId, houseId, chargeId, propertyStaffId, feeMonth, paymentStatus);
        return AjaxResult.success(result);
    }

    @PostMapping("/{communityID}")
    @ApiOperation(value = "【管理员】新增缴费详情", notes = "新增一条缴费详情记录。缴费状态——0：未缴费，1：已缴费")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "houseID", value = "房屋ID", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "chargeID", value = "收费项目ID", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "propertyStaffID", value = "物业员工ID", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "dosage", value = "用量", required = true, dataType = "Double", paramType = "query"),
            @ApiImplicitParam(name = "amount", value = "金额", required = true, dataType = "Double", paramType = "query")
    })
    public AjaxResult addChargeDetail(@RequestHeader("Authorization") String token,
                                      @RequestParam Long houseID,
                                      @RequestParam Long chargeID,
                                      @RequestParam Long propertyStaffID,
                                      @RequestParam Double dosage,
                                      @RequestParam Double amount) {
        try {
            ChargeDetail chargeDetail = new ChargeDetail();

            chargeDetail.setHouseId(houseID);
            chargeDetail.setChargeId(chargeID);
            chargeDetail.setDosage(dosage);
            chargeDetail.setAmount(amount);
            chargeDetail.setPropertyStaffId(propertyStaffID);

            boolean success = chargeDetailService.addChargeDetail(chargeDetail);
            return success ? AjaxResult.success(chargeDetail) : AjaxResult.error("新增缴费详情失败。缴费状态——0：未缴费，1：已缴费");
        } catch (Exception e) {
            return AjaxResult.error("新增缴费详情失败: " + e.getMessage());
        }
    }


    @PutMapping("/{id}/status")
    @ApiOperation(value = "【管理员】更新缴费状态", notes = "根据缴费详情记录ID更新缴费状态，只由 是否支付/管理员 来决定更新，物业没有权利更新。缴费状态——0：未缴费，1：已缴费")
    public AjaxResult updatePaymentStatus(@RequestHeader("Authorization") String token,
                                          @PathVariable Long id,
                                          @RequestParam int paymentStatus) {
        try {
            boolean updated = chargeDetailService.updatePaymentStatus(id, paymentStatus);
            return updated ? AjaxResult.success("缴费状态更新成功") : AjaxResult.error("缴费状态更新失败");
        } catch (Exception e) {
            return AjaxResult.error("缴费状态更新失败: " + e.getMessage());
        }
    }

    @GetMapping("/community/{communityId}/status/count")
    @ApiOperation(value = "【管理员】统计小区内各缴费状态的数量", notes = "根据小区ID统计各缴费状态的数量。缴费状态——0：未缴费，1：已缴费")
    public AjaxResult countPaymentStatusByCommunity(@RequestHeader("Authorization") String token,
                                                    @PathVariable Long communityId) {
        Map<Integer, Integer> statusCount = chargeDetailService.countPaymentStatusByCommunity(communityId);
        return AjaxResult.success(statusCount);
    }
}
